package carcassonne.server.http;

import carcassonne.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpRequest;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class HttpParams {

    private final Map<String, Object> params = new HashMap<>();

    public HttpParams(HttpRequest request, Map<String, String> params) {

        for (var kv : params.entrySet()) {
            if (kv.getValue() == null) continue;
            this.params.put(kv.getKey(), kv.getValue());
        }

        if (request instanceof FullHttpRequest fullHttpRequest) {
            String content = fullHttpRequest.content().toString(StandardCharsets.UTF_8);
            if (!StringUtils.IsNullOrEmpty(content)) {
                JSONObject jsonObject = JSONObject.parseObject(content);
                for (var kv : jsonObject.entrySet()) {
                    this.params.put(kv.getKey(), kv.getValue());
                }
            }
        }
    }

    public boolean Has(String key) {
        return params.containsKey(key);
    }

    public<T> T GetObject(Class<T> clazz) {
        for (Object o : params.values()) {
            if (o instanceof String json) {
                return JSON.parseObject(json, clazz);
            }
        }
        return null;
    }

    public<T> T GetObject(String key, Class<T> clazz) {
        if (!params.containsKey(key)) return null;
        return JSON.parseObject(params.get(key).toString(), clazz);
    }

    public String GetString(String key) {
        return GetString(key, "");
    }

    public String GetString(String key, String defaultValue) {
        if (!params.containsKey(key)) return defaultValue;
        return (String) params.get(key);
    }
}
